import pyperclip
import time
import sqlite3
from datetime import datetime

# SQLite数据库文件路径
DB_FILE = 'clipboard_history.db'

def init_db():
    """初始化SQLite数据库连接"""
    try:
        connection = sqlite3.connect(DB_FILE)
        cursor = connection.cursor()
        # 创建表（如果不存在）
        cursor.execute("""
            CREATE TABLE IF NOT EXISTS clipboard_history (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                content TEXT NOT NULL,
                created_at TEXT NOT NULL
            )
        """)
        connection.commit()
        return connection
    except sqlite3.Error as e:
        print(f"Database error: {e}")
        return None

def save_to_db(connection, content):
    """将内容保存到数据库"""
    try:
        cursor = connection.cursor()
        cursor.execute(
            "INSERT INTO clipboard_history (content, created_at) VALUES (?, ?)",
            (content, datetime.now().isoformat())
        )
        connection.commit()
    except sqlite3.Error as e:
        print(f"Failed to save to database: {e}")

def monitor_clipboard():
    """监听剪切板变化并保存到数据库"""
    connection = init_db()
    if not connection:
        return

    last_value = ""
    print("Clipboard monitor started. Press Ctrl+C to exit.")
    try:
        while True:
            current_value = pyperclip.paste()
            if current_value != last_value:
                print(f"Clipboard changed: {current_value}")
                save_to_db(connection, current_value)
                last_value = current_value
            time.sleep(0.5)
    except KeyboardInterrupt:
        print("\nExiting clipboard monitor...")
    finally:
        connection.close()

if __name__ == "__main__":
    monitor_clipboard()